package com.leetcode.LC_MED;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LC40 {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        ArrayList<List<Integer>> result = new ArrayList<>();
        Arrays.sort(candidates);
        backTrack(candidates, target, 0, new ArrayList<>(), result);
        return result;
    }
    private void backTrack(int[] candidates, int target, int index, List<Integer> res, List<List<Integer>> resList){
        if (target == 0){
            resList.add(new ArrayList<>(res));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            if (candidates[i] <= target){
                if(i>index&&candidates[i]==candidates[i-1]){
                    continue;
                }
                res.add(candidates[i]);
                backTrack(candidates, target-candidates[i], i+1, res, resList);
                res.remove(res.size()-1);
            }
        }
    }

    List<List<Integer>> list=new ArrayList<>();
    List<Integer> path=new ArrayList<>();
    public List<List<Integer>> combinationSum3(int[] candidates, int target) {
        Arrays.sort(candidates);
        dfs(candidates,target,0);
        return list;
    }
    private void dfs(int[] candidates, int target,int index){
        if(target==0){
            list.add(new ArrayList<>(path));
            return;
        }
        for(int i=index;i<candidates.length;i++){
            if(candidates[i]<=target){
                if(i>index&&candidates[i]==candidates[i-1]){
                    continue;
                }
                path.add(candidates[i]);
                dfs(candidates,target-candidates[i],i+1);
                path.remove(path.size()-1);
            }
        }
    }

    public static void main(String[] args) {
        LC40 lc40 = new LC40();
        List<List<Integer>> lists = lc40.combinationSum2(new int[]{10, 1, 2, 7, 6, 1, 5}, 8);
        for (List<Integer> list : lists) {
            System.out.println(list);
        }
    }
}
